package com.gaoyi.crm.fragment;

import android.os.Bundle;
import android.view.View;
import android.widget.RadioGroup;

import androidx.activity.result.ActivityResult;
import androidx.recyclerview.widget.LinearLayoutManager;

import com.gaoyi.crm.R;
import com.gaoyi.crm.adapter.RecordAdapter;
import com.gaoyi.crm.callback.IView;
import com.gaoyi.crm.constant.ApiStatus;
import com.gaoyi.crm.constant.BundleKeyName;
import com.gaoyi.crm.control.dialog.ConfirmDialog;
import com.gaoyi.crm.control.dialog.LoadingDialogUtils;
import com.gaoyi.crm.databinding.FragmentRecordsBinding;
import com.gaoyi.crm.db.dto.PmnDto;
import com.gaoyi.crm.db.query.MtcSyncedQuery;
import com.gaoyi.crm.fragment.base.BaseListFragment;
import com.gaoyi.crm.util.ToastUtil;
import com.gaoyi.crm.util.Utils;
import com.gaoyi.crm.vm.RecordViewModel;

import java.util.Date;
import java.util.Map;

public class RecordsFragment extends BaseListFragment<FragmentRecordsBinding, RecordViewModel, PmnDto, MtcSyncedQuery> implements IView {

    private RecordAdapter mAdapter;
    private ConfirmDialog mDialog;

    @Override
    protected int getLayoutId() {
        return R.layout.fragment_records;
    }

    @Override
    protected void initView() {
        mDateSearchView = mBinding.include.viewDateSearch;
        mDateSearchView.setDate(mViewModel.getStartDate().getValue(), mViewModel.getEndDate().getValue());
        mViewSearch = mBinding.include.viewSearch;
        mSmartRefreshLayout = mBinding.smartRefreshLayout;
        serTitleSort(mBinding.titleCreateDate, mBinding.titleModifyDate, mBinding.titleStatus);
        mAdapter = new RecordAdapter(mContext);
        mAdapter.setOnItemClickListener((v, position) -> mAdapter.changeSelected(position));
        mBinding.rvRecord.setLayoutManager(new LinearLayoutManager(mContext));
        mBinding.rvRecord.setItemAnimator(null);
        mBinding.rvRecord.setAdapter(mAdapter);
        MyOnClickListener onClickListener = new MyOnClickListener();
        mBinding.btnEdit.setOnClickListener(onClickListener);
        mBinding.btnDelete.setOnClickListener(onClickListener);
        mBinding.rgType.setOnCheckedChangeListener(new MyOnCheckChangeListener());
    }

    class MyOnCheckChangeListener implements RadioGroup.OnCheckedChangeListener {

        @Override
        public void onCheckedChanged(RadioGroup radioGroup, int i) {
            if (i == R.id.rb_all) {
                mQuery.setSyncedStatus(null);
            } else if (i == R.id.rb_synced) {
                mQuery.setSyncedStatus(ApiStatus.SYNC_SUCCESS);
            } else if (i == R.id.rb_save) {
                mQuery.setSyncedStatus(ApiStatus.NO_UPLOAD);
            }
            if (isPause) {
                return;
            }
            mViewModel.clearListValue();
            mQuery.init();
            mViewModel.getPmn(mQuery);
        }
    }

    class MyOnClickListener implements View.OnClickListener {

        @Override
        public void onClick(View view) {
            int id = view.getId();
            if (id == R.id.btnDelete) {
                delete();
            } else if (id == R.id.btnEdit) {
                edit();
            }
        }
    }

    private void edit() {
        Integer position = mAdapter.getCheckPosition();
        if (position == null) {
            ToastUtil.showToast(R.string.p_sel_edit_pmn);
            return;
        }
        Bundle bundle = new Bundle();
        bundle.putString(BundleKeyName.ID, mAdapter.getCurrentList().get(position).getId());
        mController.navigate(R.id.action_recordsFragment_to_editRecordFragment, bundle);
    }

    private void delete() {
        if (mAdapter.getCheckPosition() == null) {
            ToastUtil.showToast(R.string.p_sel_delete_pmn);
            return;
        }
        if (mDialog == null) {
            mDialog = ConfirmDialog.newInstance(mContext, R.string.delete_record, () -> {
                Integer position = mAdapter.getCheckPosition();
                mViewModel.delete(position, mAdapter.getCurrentList().get(position).getId());
            });
            mDialog.show(getChildFragmentManager());
        } else {
            mDialog.show();
        }
    }

    @Override
    public void onPause() {
        super.onPause();
        Utils.onPauseDialog(mDialog);
        isPause = true;
    }

    @Override
    public void onResume() {
        super.onResume();
        isPause = false;
    }

    @Override
    protected void initData() {
        if (isPause) { // 跳转后返回，SearchView会自动调用onQueryTextChange请求数据
            return;
        }
        showLoading();
        mQuery.init();
        mViewModel.getPmn(mQuery);
    }

    @Override
    protected void initLiveData() {
        mViewModel.getTotal().observe(this, totalBean -> {
            int syncTotal = 0;
            if (mBinding.rgType.getCheckedRadioButtonId() != R.id.rb_save) {
                syncTotal = totalBean.getSyncTotal();
            }
            mBinding.keyValueRecord.setValue(new String[]{getString(R.string.total_promotion, totalBean.getTotal())
                    , getString(R.string.synced_promotion, syncTotal)});
        });
        mViewModel.getResultCode().observe(this, integer -> Utils.refreshSmartRefreshLayout(mBinding.smartRefreshLayout));
        mViewModel.getList().observe(this, pmnSyncDtos -> mAdapter.submitList(pmnSyncDtos));
        // 删除record设置选中的position为null
        mViewModel.getDeleteCode().observe(this, integer -> mAdapter.setCheckPosition(null));
    }

    @Override
    protected void loadData() {
        mViewModel.getPmn(mQuery);
    }

    @Override
    protected void search(Date startDate, Date endDate) {
        mViewModel.clearListValue();
        long startTime = startDate.getTime();
        long endTime = endDate.getTime();
        mViewModel.getStartDate().setValue(startTime);
        mViewModel.getEndDate().setValue(endTime);
        mQuery.setEndDate(endTime);
        mQuery.setStartDate(startTime);
        mQuery.setKeyWord(mViewSearch.getQuery().toString());
        mQuery.init();
        mViewModel.getPmn(mQuery);
    }

    @Override
    protected void search(String keyWord) {
        mViewModel.clearListValue();
        if (mDateSearchView.isSelect()) {
            mQuery.setStartDate(mDateSearchView.getStartDate().getTime());
            mQuery.setEndDate(mDateSearchView.getEndDate().getTime());
        }
        mQuery.setKeyWord(keyWord);
        mQuery.init();
        mViewModel.getPmn(mQuery);
    }

    @Override
    protected void sort(int id, Integer sort) {
        if (id == R.id.title_create_date) {
            mQuery.setOrderByCreatedAt(sort);
        } else if (id == R.id.title_modify_date) {
            mQuery.setOrderByModifyAt(sort);
        } else if (id == R.id.title_status) {
            mQuery.setOrderBySyncStatus(sort);
        }
        mViewModel.clearListValue();
        mQuery.init();
        mViewModel.getPmn(mQuery);
    }

    @Override
    protected MtcSyncedQuery createQuery() {
        return new MtcSyncedQuery();
    }

    @Override
    protected void onRequestPermissionsResult(Map<String, Boolean> result) {

    }

    @Override
    protected void onActivityResult(int requestCode, ActivityResult result) {

    }

    @Override
    public void showLoading() {
        LoadingDialogUtils.getInstance().showLoading(mContext);
    }

    @Override
    public void hideLoading() {
        LoadingDialogUtils.getInstance().dismiss();
    }

}